<?php
/**
 * Created by PhpStorm.
 * User: jiaruo
 * Date: 17/2/15
 * Time: 下午2:04
 */
/**
 * 数组格式化后输出json.
 */
function echoJson($data){
    $errormsg =  C('msg');
    if (is_array($data)) {
        $errCode = 10000;
        $data = $data == array() ? array() :
            (is_array(reset($data)) ? $data : array($data));
    } elseif ($data === true) {
        $errCode = 10000;
        $data = array();
    } elseif (is_numeric($data)) {
        $errCode = $data;
        $data = array();
    } elseif (is_string($data) && !empty($data)) {
        $errCode = -1;
        $msg = $data;
        $data = array();
    } else {
        $errCode = -1;
        $data = array();
    }

    $msg = $msg?$msg:$errormsg[$errCode];
    $data = array(
        'errcode' => $errCode,
        'msg' => $msg,
        'result' => $data,
    );
    return $data;
}


function shouge($uid)
{

    $today = strtotime(date("Y-m-d"));
    $condition=array("uid"=>$uid,'addtime'=>array("between", array($today, $today + 86400)));
    $used=M("shouge_used")->where($condition)->count();
    if($used)
    {
       return;
    }



    //所有下级，并收取，并收割
    $uinfo=M("member")->where("id={$uid}")->find();
    $account=$uinfo["account"];


    $xiacon = array(
        'second_generation' => $account,
        'references' => $account,
        '_logic' => 'or',
    );
    $allxiaji = M("member")->field("id,account,second_generation,references")->where($xiacon)->select();
    if(!$allxiaji) return;//没有下级不需要执行

    $allson=array();//所有的儿了
    $allgrandson=array();//所有的孙子
    foreach ($allxiaji as $key => $val)
    {
        harvest($val['id']);
        if($val['references']==$account)
            $allson[]=$val['id'];
         if($val['second_generation']==$account)
             $allgrandson[]=$val['id'];
    }

    //子级加持
    if ($allson)
    {
        $today = strtotime(date("Y-m-d"));
        $sonconditon = array(
            "userid" => array("in", $allson),
            'create_time' => array("between", array($today, $today + 86400)),
            'type' => 0,
        );
        //儿子产出
        $sonout = M('brooding_log')->where($sonconditon)->sum("number");
        $ratio = C("sysreward_one");
        $sonreward = $sonout * $ratio / 100;


        if ($sonreward > 0)
        {
            $brooding = array(
                'userid' => $uid,
                'animal_on' => "son-" . $uid,
                'number' => $sonreward,
                'create_time' => time(),
                'ratio' => $ratio,
                'basenum' => $sonout,
                'type' => 7
            );
            M('brooding_log')->add($brooding);
            M("member")->where(array("id" => $uid))->setInc("currency", $sonreward);
        }
    }



    unset($sonconditon);


    //孙子加持
    if ($allgrandson)
    {
        $grandsonconditon = array(
            "userid" => array("in", $allgrandson),
            'create_time' => array("between", array($today, $today + 86400)),
            'type' => 0,
        );
        $grandsonout = M('brooding_log')->where($grandsonconditon)->sum("number");
        $grandsonratio = C("sysreward_two");
        $grandsonreward = $grandsonout * $grandsonratio / 100;
        if ($grandsonreward > 0)
        {
            $brooding = array(
                'userid' => $uid,
                'animal_on' => "grandson-" . $uid,
                'number' => $grandsonreward,
                'create_time' => time(),
                'ratio' => $grandsonratio,
                'basenum' => $grandsonout,
                'type' => 7
            );
            M('brooding_log')->add($brooding);
            M("member")->where(array("id" => $uid))->setInc("currency", $grandsonreward);
        }
    }



    $data=array("uid" =>$uid, 'addtime'=>time());

    M("shouge_used")->add($data);





}

function jiangli($uid)
{

    $uinfo=M("member")->where("id={$uid}")->find();
    $parent=$uinfo["references"];
    if(empty($parent))  return;




    $ratio=C("sysreward_one");
    //收益表中去计算
    $today = strtotime(date("Y-m-d"));
    $conditon = array(
        "userid" => $uid,
        'create_time' => array("between", array($today, $today + 86400)),
        'type' => 0,
    );
    $todayout = M('brooding_log')->where($conditon)->sum("number");

    $pidinfo=M("member")->where("account={$parent}")->find();
    if ($pidinfo)
    {
        $pid = $pidinfo['id'];


        $pcondition=array(
            "userid" => $pid,
            'animal_on' => "to-".$uid,
            'create_time' => array("between", array($today, $today + 86400)),
            'type' => 7,
        );
        $preward=M('brooding_log')->where($pcondition)->count();
        //查询今天是否已经奖励
        if ($preward == 0)
        {
            $num = $todayout * $ratio / 100;
            M('member')->where(array('id' => $pid))->setInc('currency', $num);

            if ($num > 0)
            {
                $brooding = array(
                    'userid' => $pid,
                    'animal_on' => "to-" . $uid,
                    'number' => $num,
                    'create_time' => time(),
                    'ratio' => $ratio,
                    'basenum' => $todayout,
                    'type' => 7
                );
                M('brooding_log')->add($brooding);
            }
        }
    }

    $ratio2=C("sysreward_two");
    $num2= $todayout * $ratio2 / 100;


    $grandpa=$uinfo["second_generation"];
    if(empty($grandpa)) return;

    $grandinfo=M("member")->where("account={$grandpa}")->find();
    if($grandinfo)
    {
        $grandid = $grandinfo['id'];


        $grandcondition=array(
            "userid" => $grandid,
            'animal_on' => "to-".$uid,
            'create_time' => array("between", array($today, $today + 86400)),
            'type' => 7,
        );
        $grandreward=M('brooding_log')->where($grandcondition)->count();

        if ($grandreward == 0)
        {
            M('member')->where(array('id' => $grandid))->setInc('currency', $num2);

            if ($num2 > 0)
            {
                $brooding = array(
                    'userid' => $grandid,
                    'animal_on' => "to-" . $uid,
                    'number' => $num2,
                    'create_time' => time(),
                    'ratio' => $ratio2,
                    'basenum' => $todayout,
                    'type' => 7
                );
                M('brooding_log')->add($brooding);
            }
        }

    }




}



function harvest($uid)
{
    //$uid=$this->userId;
    $putong= M('user_animal')->where(array('userid' =>$uid,'type'=>0))->count();
    //超级咖啡机
    $super= M('user_animal')->where(array('userid' =>$uid,'type'=>1))->count();
    $user['putong']=$putong;
    $user['super']=$super;



    /***********************可以收取的****************************************/
    $todayspan = strtotime(date("Y-m-d") . " 0:0:0");
    $allmachine=M('user_animal')->where(array('userid' =>$uid,'producttime'=> array( "between","100,$todayspan" )  ))->select();  //取得调制的所有机器
    foreach($allmachine as $key=>$val)
    {
        $outbase = 500;//默认生产基数
        $machinnumber=0;



        $list = M('product_ratio')->where(array('start'=>array('elt',strtotime(date('Y-m-d',$val['producttime']). " 0:0:0"))))->order('id desc')->find();
        $ratio=$list["ratio"];//计算当天利率

        if (0 == $val["type"])
        {
            $outbase = C("comonOut");
            $machinnumber=$putong;
        } //普通机器的产出基数
        if (1 == $val["type"])
        {
            $outbase = C("superout");//超级机器的产出基数
            $machinnumber=$super;
            $ratio+=C("superration");  //超级机较高的产出率

        }






        $outbase += $val["store"];//当前机器存储量
        $outkafei = kafeiout($outbase,$machinnumber,$ratio);//产出咖啡
        if(($outbase+$outkafei)>$val['maxoutput']) //查看是否超过最大值，如果超地最大值，则扔掉
        {
            $outkafei=$val['maxoutput']-$outbase;
        }

		if($outkafei>0)
		{
			
			$brooding = array(
				'userid' => $uid,
				'animal_on' => $val['animal_on'],
				'number' => $outkafei,
				'create_time' => time(),
				'ratio' =>$ratio,
				'basenum' => $outbase
			);
			M('brooding_log')->add($brooding);


			M('user_animal')->where(array('id' =>$val['id']))->setInc("store", $outkafei);//存储增加
			M('user_animal')->where(array('id' =>$val['id']))->setInc("hatchery", $outkafei);//生产增加
			M('user_animal')->where(array('id' =>$val['id']))->save(array("producttime"=> 0));//设置成为可以调制
	}


    }
    /***************************************************************/

    //     die( json_encode( array("errcode"=>200,'msg'=>'收取成功！')));

}


